from alipay import AliPay
from django.http import JsonResponse,HttpResponse
from django.shortcuts import render
from meiduo_mall import settings
from apps.orders.models import OrderInfo
from utlis.views import LoginRequiredJSONMixin
# Create your views here.
from django.views import View


class PaymentView(LoginRequiredJSONMixin,View):
    """对接支付宝跳转支付链接"""
    def get(self,request,order_id):
        user = request.user
        # 查询要支付的订单
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return HttpResponse('订单信息错误')

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            app_notify_url=None,  # 默认回调url
            sign_type="RSA2",
            debug=True
        )
        # 生成支付链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        alipay_url = settings.ALIPAY_URL+"?"+order_string

        return JsonResponse({'code':0,'errmsg':'ok','alipay_url':alipay_url})


